package com.lancoo.znbkxx.teacher.ui.activity

import android.content.Context
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.base.BaseVMActivity
import com.lancoo.znbkxx.teacher.databinding.ActivityPaperSearchBinding
import com.lancoo.znbkxx.teacher.ui.fragment.BasicPaperFragment
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import com.lancoo.znbkxx.teacher.widget.PaperFilterWindow

import kotlinx.android.synthetic.main.activity_paper_search.*
import kotlinx.android.synthetic.main.view_filter_paper.view.*


/**
 * @author : Admin
 * @date   : 2019/8/1 10:11
 * @desc   :
 */
class SearchActivity : BaseVMActivity<PaperViewModel, ActivityPaperSearchBinding>(),
        View.OnClickListener, TextView.OnEditorActionListener, RadioGroup.OnCheckedChangeListener {
    private val mInputManager by lazy {
        getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    }
    private var publish = -1
    private var finish = -1
    private var layer = -1
    private var searchInfo = ""
    private val filterPopupWindow by lazy { PaperFilterWindow(this, this, this) }
    private var mLastSearchTime: Long = 0
    private val basicPaperFragment by lazy {
        BasicPaperFragment().apply {
            arguments = bundleOf(Pair("layer", layer), Pair("publish", this@SearchActivity.publish),
                    Pair("finish", this@SearchActivity.finish), Pair("from", "search"),
                    Pair("searchInfo", this@SearchActivity.searchInfo))
        }
    }

    override fun providerVMClass(): Class<PaperViewModel>? {
        return PaperViewModel::class.java
    }

    override fun setLayoutID(): Int {
        return R.layout.activity_paper_search
    }


    override fun initView() {
        publish = intent.getIntExtra("publish", -1)
        finish = intent.getIntExtra("finish", -1)
        layer = intent.getIntExtra("layer", -1)
        intent.getStringExtra("keywords")?.let { searchInfo = it }
        edt_search.setText(searchInfo)
        ibn_search.setOnClickListener(this)
        iv_close.setOnClickListener(this)
        tv_search.setOnClickListener(this)
        edt_search.clearFocus()
        edt_search.setOnEditorActionListener(this)
//        edt_search.addTextChangedListener(this)
        initFragment()
    }

    private fun initFragment() {
        vp_paper.adapter = object : FragmentStateAdapter(supportFragmentManager, lifecycle) {
            override fun getItemCount(): Int {
                return 1
            }

            override fun createFragment(position: Int): Fragment {
                return basicPaperFragment
            }
        }
    }

    private fun searchData(publish: Int, finish: Int, searchInfo: String) {
        (supportFragmentManager.findFragmentByTag("f0") as BasicPaperFragment).apply {
            this.publish = publish
            this.finish = finish
            this.searchInfo = searchInfo
            initPaper(publish, finish, searchInfo)
        }
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            R.id.tv_search, R.id.ibn_search -> {
                initChecked()
                filterPopupWindow.showAsDropDown(binding.linearLayout, 0, 0)
            }
            R.id.iv_reset -> reSet()
            R.id.iv_config -> {
                loadingDialog.show()
                filterPopupWindow.dismiss()
                searchData(publish, finish, searchInfo)
            }
            R.id.iv_close -> finish()
        }
    }

    private fun initChecked() {
        when (publish) {
            -1 -> filterPopupWindow.contentView.rb_publish_all.isChecked = true
            0 -> filterPopupWindow.contentView.rb_unpublished.isChecked = true
            1 -> filterPopupWindow.contentView.rb_published.isChecked = true
        }
        when (finish) {
            -1 -> filterPopupWindow.contentView.rb_finish_all.isChecked = true
            0 -> filterPopupWindow.contentView.rb_unfinished.isChecked = true
            1 -> filterPopupWindow.contentView.rb_finished.isChecked = true
        }
    }

    private fun reSet() {
        (filterPopupWindow.contentView.rg_publish.getChildAt(0) as RadioButton).isChecked = true
        (filterPopupWindow.contentView.rg_finish.getChildAt(0) as RadioButton).isChecked = true
    }

    override fun onCheckedChanged(group: RadioGroup?, checkedId: Int) {
        when (checkedId) {
            R.id.rb_publish_all -> publish = -1
            R.id.rb_unpublished -> publish = 0
            R.id.rb_published -> publish = 1
            R.id.rb_finish_all -> finish = -1
            R.id.rb_unfinished -> finish = 0
            R.id.rb_finished -> finish = 1
        }
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            searchInfo = binding.edtSearch.text.toString()
            searchPaperByKeyword(binding.edtSearch.text.toString().trim())
        }
        hideKeyboard()
        binding.edtSearch.clearFocus()
        return true
    }

//    override fun afterTextChanged(s: Editable?) {
//        if (s.toString().isNotEmpty()) {
//            searchPaperByKeyword(s.toString().trim())
//        }
//    }
//
//    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
//    }
//
//    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
//    }

    private fun searchPaperByKeyword(keyWords: String) {
        if (System.currentTimeMillis() - mLastSearchTime > 1000) {
            mLastSearchTime = System.currentTimeMillis()
        } else {
            return
        }
        if (keyWords.isNotEmpty()) {
            loadingDialog.show()
            searchInfo = keyWords
            searchData(publish, finish, searchInfo)
        }
    }

    private fun hideKeyboard() {
        mInputManager.hideSoftInputFromWindow(
                currentFocus!!.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
        )
    }
}